package com.zipking.cloud.springbootmybatis.util.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpHeaders;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class EasyExcelUtilExt {
    @Data
    @Builder
    public static class ExcelParam {
        /**
         * 查询 Mapper
         */
        private BaseMapper baseMapper;

        /**
         * Lambda查詢方式
         */
        private LambdaQueryWrapper lambdaQueryWrapper;

        /**
         * 页码，默认从1开始
         */
        private Integer pageNo = 1;

        /**
         * 分页条数，,默认每个sheet 1000 条数据
         */
        private Integer pageSize = 1000;

        /**
         * 用于存放查询到的結果，让Excel生成
         */
        private Class<?> respClazz;

        /**
         * 生成的Excel 名称，不加后缀
         */
        private String fileName;

        /**
         * Excel sheet名称
         */
        private String sheetName;
    }

    public static void exportExcel(ExcelParam excelParam, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + excelParam.getFileName() + ".xlsx");
        try   {
            ServletOutputStream outputStream = response.getOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(outputStream, excelParam.getRespClazz()).build();
            Page page = new Page(excelParam.getPageNo(), excelParam.getPageSize());
            page = (Page) excelParam.getBaseMapper().selectPage(page, excelParam.getLambdaQueryWrapper());
            /** 构建 */
            WriteSheet writeSheet1 = EasyExcel.writerSheet(1, excelParam.getSheetName() + "第" + excelParam.getPageNo() + "页").build();
            /** 获取总数 */
            Long totalPage = page.getPages();
            List records = page.getRecords();
            /** 写入内容 */
            excelWriter.write(records, writeSheet1);
            writeSheet1 = null; // GC
            // 若为空表
            if (CollUtil.isEmpty(page.getRecords())) {
                /** 生成完毕 */
                excelWriter.finish();
                /** 立即刷回 */
                outputStream.flush();
                return;
            }
            for (int i = excelParam.pageNo + 1, index = 2; i <= totalPage; i++, index++) {
                /** 清空*/
                records.clear();
                WriteSheet writeSheet = EasyExcel.writerSheet(index, excelParam.getSheetName() + "第" + i + "页").build();
                page.setCurrent(i);
                /** 新的查询 */
                page = (Page) excelParam.getBaseMapper().selectPage(page, excelParam.getLambdaQueryWrapper());
                records = page.getRecords();
                /** 输入内容內容 */
                excelWriter.write(records, writeSheet);
            }
            /** 生成完毕 */
            excelWriter.finish();
            /** 立即刷回 */
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

